"""
Created on 26-Jan-2010

@author: dexen
"""
import sys
import time
import threading as th

from dexen.system.common.meta import JobMeta


#===============================================================================
# Units
#===============================================================================
class InUnit(object):
    def __init__(self, job_id, transact, master_state):
        self.job_id = job_id
        self.transact = transact
        self.master_state = master_state

class OutUnit(object):
    def __init__(self, job_id, transact):
        self.job_id = job_id
        self.transact = transact


#===============================================================================
# SlaveComm
#===============================================================================
class SlaveComm(object):
    def __init__(self):
        self.lock = th.Lock()
        self.in_unit = None #transact coming from master to be processed
        self.out_unit = None #transact resulting from the execution on slave
        self.jobs = {} # job_id:JobMeta
        self.recent_jobs = [] # list of job_ids
        
    def add_job(self, job_meta):
        with self.lock:
            assert isinstance(job_meta, JobMeta)
            self.jobs[job_meta.get_id()] = job_meta
            self.recent_jobs.append(job_meta.get_id())
        
    def get_jobs(self):
        with self.lock:
            jobs = []
            for id in self.recent_jobs:
                jobs.append(self.jobs[id])
            self.recent_jobs = []
        return jobs
        
    def set_in_unit(self, unit):
        with self.lock:
            self.in_unit = unit
            
    def get_in_unit(self):
        with self.lock:
            unit = self.in_unit
            self.in_unit = None
            return unit
                
    def set_out_unit(self, unit):
        with self.lock:
            self.out_unit = unit

    def get_out_unit(self):
        with self.lock:
            unit = self.out_unit
            self.out_unit = None
            return unit
    
    def test(self, task_meta):
        with self.lock:
            self.tm = task_meta
    

#===============================================================================
# Testing
#===============================================================================
def test():
    pass

if __name__ == "__main__":
    test()
